<?php
namespace app\admin\controller;

use app\admin\model\WelfareM as WelfareMModel;
use app\admin\model\WelfareType as WelfareType;
use Db;
use Request;

/**
 * 福利操作，主要金币元宝类操作
 * WelfareM/index 显示
 * WelfareM/add  申请
 * WelfareM/delete 删去
 * WelfareM/audit 审核
 * WelfareM/quickedit 快捷备注
 * WelfareM/quicksend 发送
 * WelfareM/delall 批量删去
 * WelfareM/auditall 批量审核
 * WelfareM/sendall 批量发送
 */
class WelfareM extends Base
{
    private $partitionid; //当前区id
    public function initialize()
    {
        parent::initialize();
        $this->partitionid = session('partitionid'); //别名：避免与控制名冲突
        if (empty($this->partitionid)) {return $this->error('参数错误,请先选择分区，然后再操作', 'Partition/index');}

    }
    /*
    显示分类信息列表
     */
    public function index($act = "")
    {
        $where = [];
        if (Request::has('search')) {
            $where[] = ['name', 'like', '%' . trim(Request::param('search/s', '', 'strip_tags')) . '%'];
        }

		$where[] = ['partitionid','=',$this->partitionid];

        //$list = WelfareMModel::alias('a')->field('a.*,b.title as typename')->join('arctype b', 'b.id = a.typeid', 'left')->order('id desc')->where($where)->paginate(20);
        $list   = WelfareMModel::order('id desc')->where($where)->paginate(config('webconfig.page'), false, ['query' => Request::param()]);
        $search = Request::param('search/s', '', 'strip_tags') ?? "";
        foreach ($list as $k => $v) {
            $list[$k]['type']      = $v->WelfareType->name; //类型名
            $list[$k]['auditorid'] = Db::name('user')->where('id', $v['auditorid'])->value('nickname') ?? $v['auditorid'];

            $list[$k]['applicantid'] = Db::name('user')->where('id', $v['applicantid'])->value('nickname') ?? $v['applicantid'];
			$list[$k]['partition'] = $v->partition->name;
        }
        //print_r($list);

        $this->assign([
            'list'   => $list,
            'page'   => $list->render(),
            'search' => $search,
        ]);
        return $this->fetch();
    }
    /*
    信息添加
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $post   = $this->request->post();
            $result = $this->validate($post, 'app\admin\validate\WelfareM');
            if (true !== $result) {
                return $this->error($result);
            }
            $list = [];
            if ((strpos($post['names'], ',') !== false)) {
                $names = array_filter(explode(',', $post['names']));
                foreach ($names as $k => $v) {
                    $list[] = [
                        'name'        => $v,
						'partitionid' => $this->partitionid,
                        'type'        => $post['type'],
                        'num'         => $post['num'],
                        'remark'      => $post['remark'],
                        'applicantid' => session('userid'),
                        'create_time' => time(),
                    ];
                }
                $WelfareMModel = new WelfareMModel;
                $data          = $WelfareMModel->saveAll($list);
            } else {
                $post['name']        = $post['names']; //申请人
                $post['applicantid'] = session('userid'); //申请人
				$post['partitionid'] = $this->partitionid; //区
                $post['create_time'] = time();
                $data                = WelfareMModel::create($post);
            }

            if (!empty($data)) {
                return $this->success('添加成功', 'admin/WelfareM/index');
            } else {
                return $this->error('添加失败');
            }
        }
        $data = WelfareType::where('status', 1)->select();
        $this->assign('type', $data);
        return $this->fetch();
    }

    /**
     * 审核操作
     * @return [type] [description]
     */
    public function audit()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if (Request::isPost()) {
            if (Request::has('status') == 1) {
                $data = [
                    'id'          => Request::post('id/d'),
                    'status'      => Request::post('status'),
                    'update_time' => time(),
                    'auditorid'   => session('userid'), //审核人
                ]; //状态
                if (Db::name('welfare_m')->where('id', Request::post('id/d'))->value('status') != 1) {
                    //防止再次审核
                    $model               = WelfareMModel::update($data);
                    $data['update_time'] = date('Y-m-d H:i:s', $data['update_time']);
                    $data['auditorid']   = Db::name('user')->where('id', session('userid'))->value('nickname') ?? $data['auditorid'];
                }
                $msg = "福利审核";
            }
            if (!empty($model)) {
                $sendcode = $this->send($id); //发送状态
                $data['cdata'] = $sendcode['cdata'];
                if ($sendcode['code']) {
                    $data['cdata'] = $sendcode['cdata'];
                    return $this->success($sendcode['msg'], '', $data);
                } else {
                    return $this->success($msg . '成功---因'.$sendcode['msg'].'发送失败', '', $data);
                }
            } else {
                return $this->error($msg . '失败');
            }
        }
    }
    /**
     * 快捷修改备注
     * @return [type] [description]
     */
    public function quickedit()
    {
        if (Request::isPost()) {
            if (Request::has('remark')) {
                $data  = ['id' => Request::post('id/d'), 'remark' => Request::post('remark')]; //备注
                $model = WelfareMModel::update($data);
                $msg   = "备注修改";
            }
        }
        if (!empty($model)) {
            return $this->success($msg . '成功', '', $data);
        } else {
            return $this->error($msg . '失败');
        }

    }

    /**
     * 快捷操作发送
     * @return [type] [description]
     */
    public function sendstatus()
    {
        if (Request::isPost()) {
            $id = Request::post('id/d');
            return json($this->send($id));
        }
    }

    private function send($id)
    {
        $url = $this->partitionurl();
        if (!$url) {
            //return $this->error('分区或平台地址没有设置');
            return ['code' => 0, "cdata" => "", 'msg' => "分区或平台地址没有设置"];
        }

        //if (Request::isPost()) {
        //$id   = Request::post('id/d');
        $info = WelfareMModel::where([['id', '=', $id], ['status', '=', 1], ['sendstatus', '<>', 1]])->find();

        $data = [
            'name' => $info['name'], //角色
            'type' => $info['type'], //类型
            'num'  => $info['num'], //数量
        ];

        if (empty($info)) {return ['code' => 0, "cdata" => "", 'msg' => "没有要发送的数据"];}
        $postinfo = request_post($url, $data);
        if (empty($postinfo)) {return ['code' => 0, "cdata" => "", 'msg' => "提交错误".$postinfo];}
        $pos = json_decode($postinfo, true);
        if ($pos['code'] == 1) {
            $data  = ['id' => $id, 'sendstatus' => 1]; //备注
            $model = WelfareMModel::update($data);
            $msg   = "发送成功";
            $cdata = 1;
        } else {
            $data  = ['id' => $id, 'sendstatus' => 2]; //备注
            $model = WelfareMModel::update($data);
            $msg   = "发送失败,错误代码".$pos['code'];
            $cdata = 2;
        }
        return ['code' => 1, "cdata" => $cdata, 'msg' => $msg];
        //return $this->success($msg, 'admin/WelfareM/index', $cdata);
        //}
    }

    private function partitionurl()
    {
        $id           = $this->partitionid;
        $partitionurl = Db::name('partition')->where([['status', '=', 1], ['id', '=', $id]])->value('http');
        if (empty($partitionurl)) {
            //$partitionurl = Db::name('partition')->where([['status','=',1],['id','=',$id]])->value('platform_id');
            $info         = Db::name('partition')->field("b.http as http")->alias('a')->join('platform b', 'a.platform_id = b.id', 'left')->where([['a.status', '=', 1], ['b.status', '=', 1]])->find();
            $partitionurl = $info['http'];
        }
        if (empty($partitionurl)) {
            return false;
        } else {
            return $partitionurl;
        }
    }

    /*
    信息删去
     */
    public function delete($value = '')
    {
        $id   = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $data = WelfareMModel::get($id); // 获取要删除的对象  不存在时返回 null    $user::destroy($id) //批量删时尽量用，返回记录条数，没有删除返回0
        if (!empty($data)) {
            if ($data->delete()) {
                return $this->success('删去成功', 'admin/WelfareM/index');
            }
        }
        return $this->error('删去失败');
    }

    /**
     * 批量删去
     * @param  string $ids [description]
     * @return [type]      [description]
     */
    public function delall($ids = '')
    {
        $ids  = !empty($ids) ? $ids : '';
        $data = WelfareMModel::destroy($ids);
        if (!empty($data)) {
            return $this->success('删去成功', 'admin/WelfareM/index');
        }
        return $this->error('删去失败');
    }

    /**
     * 批量审核
     * @param  string $ids [description]
     * @return [type]      [description]
     */
    public function auditall($ids = '')
    {
        //$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $ids           = !empty($ids) ? $ids : '';
        $list          = [];
        $i             = 0;
        $WelfareMModel = new WelfareMModel;
        if (Request::isPost()) {
            $idsarr = explode(",", $ids);
            //print_r($idsarr);
            foreach ($idsarr as $k => $v) {
                if (Db::name('welfare_m')->where('id', $v)->value('status') != 1) {
                    $list[] = [
                        'id'          => $v,
                        'status'      => 1,
                        'update_time' => time(),
                        'auditorid'   => session('userid'), //审核人
                    ];
                    $i++;
                }
            }
            //print_r($list);
            if($i == 0){return $this->error('没有要审核数据');}
            $data = $WelfareMModel->saveAll($list);

            $msg = "批量审核" . $i . "条信息";
            if (!empty($data)) {
                $j = 0;
                foreach ($idsarr as $k1 => $v1) {
                    $sendcode = $this->send($v1); //发送状态
                    if ($sendcode['code']) {
                        $j++;
                    } else {
                        continue;
                    }
                }
                $msg .= "-----成功发送" . $j . "条记录";
                return $this->success($msg , 'admin/WelfareM/index');
            } else {
                return $this->error($msg);
            }
        }
    }

    /**
     * 批量发送
     * @return [type] [description]
     */
    public function sendall($ids = '')
    {
        $ids           = !empty($ids) ? $ids : '';
        $WelfareMModel = new WelfareMModel;
        if (Request::isPost()) {
            $idsarr = explode(",", $ids);
            $i      = 0;
            //$j      = 0;
            foreach ($idsarr as $k => $v) {
                $sendcode = $this->send($v); //发送状态
                if ($sendcode['code']) {
                    $i++;
                } else {
                    continue;
                }
            }
            $msg = "共有" . $i . "条发送成功,";
            if (!empty($data)) {
                return $this->success($msg, 'admin/WelfareM/index', $data);
            } else {
                return $this->error($msg);
            }
            //$data = $WelfareMModel->saveAll($list);
        }
    }



}
